package main

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/auth/service"
	pb "github.com/micro/go-micro/v2/auth/service/proto"
	"github.com/micro/go-micro/v2/client"
	"github.com/micro/go-micro/v2/util/log"
	"github.com/micro/go-micro/v2/web"
	_ "github.com/micro/go-plugins/registry/eureka/v2"
	user "github.com/morphyguo/demo/api/user/login"
	"github.com/morphyguo/demo/commons"
	server "github.com/morphyguo/demo/srv/user/proto"
	"net/http"
	"strconv"
)


func handler(cl client.Client) http.Handler {
	info := &user.Info{cl}

	r := gin.Default()

	r.Handle("GET", "/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"msg": "OK"})
	})
	r.Handle("GET", "/user/:id", func(c *gin.Context) {
		cli := server.NewUserService(commons.NsSrvUser, cl)
		id, _ := strconv.ParseInt(c.Param("id"), 10, 32)
		id32 := int32(id)
		if resp, err := cli.GetUserById(context.TODO(), &server.UserRequest{Id: id32}); err == nil {
			c.JSON(http.StatusOK, resp)
		} else {
			c.JSON(http.StatusOK, gin.H{"code": -1, "msg": "error"})
		}
	})

	r.Handle("GET", "/rules", func(i *gin.Context) {
		cli := pb.NewRulesService(commons.NsSrvAuth, cl)
		if rsp,err := cli.List(context.TODO(), &pb.ListRequest{
		}); err != nil {
			log.Warn("request rules list fail %v",err)
		} else {
			i.JSON(http.StatusOK, rsp)
		}
	})

	r.Handle("GET", "/login", info.Login)
	return r
}

type logWrapper struct {
	client.Client
}

func (l *logWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
	log.Info("call here for test")
	return l.Client.Call(ctx, req, rsp, opts...)
}

func wraplog(c client.Client) client.Client {
	return &logWrapper{c}
}

func main1() {
	cs := micro.NewService(micro.WrapClient(func(c client.Client) client.Client {
		return wraplog(c)
	}), micro.Auth(service.NewAuth()), micro.Name(commons.NsWebUser), micro.Cmd(c))
	s := web.NewService(web.Address(":8083"),web.Name(commons.NsWebUser),
		web.MicroService(cs),
	)

	s.Init()

	s.Handle("/", handler(s.Options().Service.Client()))

	if err := s.Run(); err != nil {
		log.Fatal("start user service err", err)
	}
}
